﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using AR.Web.Services;
using AR.Entities;
using AR.Helpers;

namespace AR.Views.EntretienOrale.PerimetreEntretien
{
    public partial class GDC_SI_MSSKILLS : Page
    {
        List<int> GCM = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        List<string> Appreciation = new List<string> { "Non satisfaisant", "Passable", "Bien", "Tres bien" };

        
        public GDC_SI_MSSKILLS()
        {
            if (WebContext.Current.User.IsAuthenticated)
            {
                if (WebContext.Current.User.IsInRole("Admin") || WebContext.Current.User.IsInRole("SolutionManager"))
                {
                    InitializeComponent();
                    this.candidatOK.IsChecked = true;
                }
                else
                {
                    AR.NavigationService.Navigate("/ListeCandidats");
                    
                    ((MainPage)(Application.Current.RootVisual)).ContentFrame.Navigate(new Uri("/ListeCandidats", UriKind.Relative));
                }
            }
            else
            {
                AR.NavigationService.Navigate("/LoginPage");
            }
        }



        public static int ExtractNote(string name)
        {
            string lastChar = name.Substring(name.Length - 1);
            if (int.Parse(lastChar) == 1)
                return 3;
            else if (int.Parse(lastChar) == 2)
                return 2;
            else if (int.Parse(lastChar) == 3)
                return 1;
            else
                return 0;
        }

        public string getRemarquebyPosition(int position)
        {

            switch (position)
            {
                case 1:
                    return this.A1Rem.Text;
                case 2:
                    return this.A2Rem.Text;
                case 3:
                    return this.A3Rem.Text;
                case 4:
                    return this.B1Rem.Text;
                case 5:
                    return this.B2Rem.Text;
                case 6:
                    return this.B3Rem.Text;
                case 7:
                    return this.B4Rem.Text;
                case 8:
                    return this.B5Rem.Text;
                case 9:
                    return this.C1Rem.Text;
                case 10:
                    return this.C2Rem.Text;
                case 11:
                    return this.C3Rem.Text;
                case 12:
                    return this.C4Rem.Text;
                default:
                    return "NULL";

            }

        }

        public static int ExtractUV(string name)
        {
            string str = name.Substring(0, 2);
            switch (str)
            {
                case "A1":
                    return 3;
                case "A2":
                    return 2;
                case "A3":
                    return 1;
                case "B1":
                    return 3;
                case "B2":
                    return 2;
                case "B3":
                    return 3;
                case "B4":
                    return 3;
                case "B5":
                    return 1;
                case "C1":
                    return 2;
                case "C2":
                    return 1;
                case "C3":
                    return 1;
                case "C4":
                    return 2;
                default:
                    return -1;

            }
        }

        public static double calculTotal(List<RadioButton> liste)
        {
            double total = 0;
            for (int i = 0; i < liste.Count; i++)
            {
                total = total + (ExtractNote(liste.ElementAt(i).Name) * ExtractUV(liste.ElementAt(i).Name));
            }

            return total / 24;

        }


        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            List<RadioButton> group = this.Descendents().OfType<RadioButton>().Where(r => r.IsChecked == true && r.Name != "candidatOK" && r.Name != "candidatKO").ToList();
            if (group.Count < 12) errorMessageLabel.Visibility = Visibility.Visible;
            else
            {
                double totalNote = calculTotal(group);
                EntretienOraleContext contextEO = new EntretienOraleContext();
                CandidatContext contextCan = new CandidatContext();
                ENTRETIEN_ORALE entretien = new ENTRETIEN_ORALE();
                ENT_ORALE_CRITERE critere;

                string sid = NavigationContext.QueryString["id"];
                int id = int.Parse(sid);
                entretien.ID_CANDIDAT = id;
                entretien.DATE_ENTRETIEN = DateTime.Today;
                entretien.NOTE = new decimal(Math.Round(totalNote, 2));
                entretien.USER_NAME = WebContext.Current.User.Name;
                //entretien.APPRECIATION = cmbApprec.SelectedItem.ToString();
                entretien.APPRECIATION = Appreciation[(int)(cmbApprec.Value*4)-1];
                for (int i = 1; i <= group.Count; i++)
                {
                    critere = new ENT_ORALE_CRITERE();
                    critere.IDCRITERE = i;
                    critere.NOTE = ExtractNote(group.ElementAt(i - 1).Name).ToString();
                    critere.ID_ENT_OR = entretien.ID_ENT_OR;
                    if (!(string.IsNullOrEmpty(getRemarquebyPosition(i))))
                    {
                        critere.REMARQUE = getRemarquebyPosition(i);
                    }
                    contextEO.ENT_ORALE_CRITEREs.Add(critere);

                }


                contextEO.ENTRETIEN_ORALEs.Add(entretien);
                contextEO.SubmitChanges().Completed += (send, args) =>
                {
                    var query = contextCan.GetCandidatByIDQuery(int.Parse(sid));
                    contextCan.Load(query).Completed += (sender2, ev) =>
                    {
                        CANDIDAT candidat = contextCan.CANDIDATs.SingleOrDefault();
                        candidat.GCM_ESTIMEE_SM = decimal.Parse(cmbGCM.SelectedItem.ToString());
                        candidat.ID_STATUT = 2;
                        if (this.candidatOK.IsChecked == true)
                            candidat.ETAT_ENTRETIEN_ORALE = 1;
                        else
                        {
                            candidat.ETAT_ENTRETIEN_ORALE = 1; // à revoir pour couleur vert validé / rouge echec
                            candidat.ID_STATUT = 3; // Entretien orale non réussie
                        }

                        // candidat.ValidateEmployee(contextCan.ValidationContext);
                        // contextCan.ValidationContext.Items.Clear();
                        contextCan.SubmitChanges().Completed += (Sender, Arg) =>
                        {
                            Tools.AfficheNotificationFlash(string.Format("L'entretien orale du candidat {0} {1} est terminé", candidat.NOM, candidat.PRENOM),4);
                            AR.NavigationService.Navigate("/ListeCandidats");
                        
                        };
                    };

                };

                // btnEnregistrer.NavigateUri = new Uri("/EntretienOrale", UriKind.Relative); 

            }

        }







        // S'exécute lorsque l'utilisateur navigue vers cette page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {


            {

                for (int i = 0; i < GCM.Count; i++)
                {
                    cmbGCM.Items.Add(GCM.ElementAt(i));
                }

                //for (int i = 0; i < Appreciation.Count; i++)
                //{
                //    cmbApprec.Items.Add(Appreciation.ElementAt(i));
                //}
                cmbGCM.SelectedItem = cmbGCM.Items.ElementAt(0);
                //cmbApprec.SelectedItem = cmbApprec.Items.ElementAt(1);


                CandidatContext context = new CandidatContext();
                string sid = NavigationContext.QueryString["id"];
                var query = context.GetCandidatByIDQuery(int.Parse(sid));
                context.Load(query).Completed += (sender, ev) =>
                {

                    CANDIDAT candidat = context.CANDIDATs.SingleOrDefault();

                    this.titreEntretien.Content = candidat.NOM + " " + candidat.PRENOM + " , Practice : " + candidat.PRACTICE.PRACTICE1;
                };





            }
        }



    }

    public static class VisualTreeEnumeration
    {
        public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
        {
            int count = VisualTreeHelper.GetChildrenCount(root);
            for (int i = 0; i < count; i++)
            {
                var child = VisualTreeHelper.GetChild(root, i);
                yield return child;
                foreach (var descendent in Descendents(child))
                    yield return descendent;

            }
        }
    }
}

